# _*_ coding:utf-8 _*_
# @Time  : 2022.07.28
# @Author: zizlee
import itertools
from db import FAConnection
from collections import Counter
from v1_all_api.all_utils import datetime_utils


# 查询用户所在的组及其组员
def get_operator_group_members(user_id, query_date):
    # 查询用户小组下的组员
    group_sql = """
            SELECT id,user_id,group_en,is_leader,admin_name FROM work_user_extend 
            WHERE group_en=(SELECT group_en FROM work_user_extend WHERE user_id=%s) 
            AND end_date>=%s;
        """
    db_conn = FAConnection()
    group_users = db_conn.query(group_sql, param=[user_id, query_date.replace('-', '')])
    # 验证查询者是不是组长
    is_leader = False
    for user in group_users:
        if user['is_leader'] == 1 and user['user_id'] == user_id:
            is_leader = True
            break
    return group_users, is_leader


# 计算评级的和
def calculate_levels_sum(list_level: list):
    container = []
    for s in list_level:
        if not s:
            continue
        for cr in ['A', 'B', 'C', 'D', 'E', 'F']:
            s = s.replace(cr, f'*{cr}-')
        for sub in s.split('-'):
            if not sub:
                continue
            sl = sub.split('*')
            container.extend(int(sl[0]) * [sl[1]])
    container.sort()
    return ''.join(['%d%s' % (v, k) for k, v in Counter(container).items() if k])


# 对数据按人员、月份进行统计
def statistics_monthly(records, month_list, running_count=False, flag=False):
    user_names = {}
    user_data = {}
    for row in records:
        if flag:
            row['month'] = row['create_time'].strftime('%Y%m')
        else:
            row['month'] = str(row['create_date'])[:6]
            row['creator'] = row['user_id']

        if row['creator'] in user_data.keys():
            user_data[row['creator']].append(row)
        else:
            user_data[row['creator']] = [row]
        user_names[row['creator']] = row['admin_name']

    statistics_data = []
    # 对各个useData数据进行月份统计{month:0,count:0,running:0}
    for uid, udata in user_data.items():
        udata.sort(key=lambda x: x['month'])
        month_data = {}
        total_count, total_running_count = 0, 0
        for m, mdata in itertools.groupby(udata, key=lambda x: x['month']):
            month_objs = list(mdata)
            month_count = len(month_objs)
            month_data[f'count_{m}'] = month_count
            if running_count:
                month_running_count = len(list(filter(lambda i: not i['close_time'], month_objs)))
                month_data[f'running_{m}'] = month_running_count
        for month in month_list:
            month_count = month_data.get(f'count_{month}')
            show_text = ''
            if month_count:
                show_text += str(month_count)
                total_count += month_count
            if running_count:
                month_running_count = month_data.get(f'running_{month}')
                if month_running_count:
                    show_text += f' ({month_running_count})'
                    total_running_count += month_running_count
            month_data[month] = show_text
        total_show_text = ''
        if total_count:
            total_show_text += str(total_count)
        if total_running_count and running_count:
            total_show_text += f' ({total_running_count})'
        statistics_data.append({
            'user_id': uid,
            'admin_name': user_names[uid],
            'total_count': total_count,
            'total_running': total_running_count,
            'total_show_text': total_show_text,
            **month_data.copy()
        })

    # 增加合计数
    table_columns = []
    sum_obj = {
        'user_id': -1,
        'admin_name': '合计',
        'total_count': 0,
        'total_running': 0,
        'total_show_text': ''

    }
    tt, ttn = 0, 0  # 月份的所有合计
    for m in month_list:
        table_columns.append({'prop': m, 'label': m})
        total_month, total_month_running = 0, 0
        for u in statistics_data:
            total_month += u.get(f'count_{m}', 0)  # 所有人的当月总计
            total_month_running += u.get(f'running_{m}', 0)  # 所有人的当月运行总计
        sum_obj[f'count_{m}'] = total_month
        sum_obj[f'running_{m}'] = total_month_running

        t_show = ''
        if total_month:
            t_show += str(total_month)
        if total_month_running and running_count:
            t_show += f' ({total_month_running})'
        sum_obj[m] = t_show

        tt += total_month
        ttn += total_month_running
    tt_show_text = ''
    if tt:
        tt_show_text += str(tt)
    if ttn and running_count:
        tt_show_text += f' ({ttn})'
    sum_obj['total_show_text'] = tt_show_text

    statistics_data.append(sum_obj)  # 将合计数加入行

    table_columns.insert(0, {'prop': 'admin_name', 'label': '姓名'})
    table_columns.append({'prop': 'total_show_text', 'label': '小计'})
    return statistics_data, table_columns


# 协同服务的名称
def get_module_name(module_key: str):
    return {
        'Lecture': '演讲培训',
        'Accompany': '陪同走访',
        'InvestmentPlan': '投资计划',
        'Hedging': '套保方案',
        'CustomerOnline': '产业客户线上服务',
        'AnalysisReport': '分析报告',
        'PPTCourseware': 'PPT课件',
        'DataNeed': '材料需求',
        'WxGroup': '微信交流群',
        'WindRemote': 'wind远程',
        'Ruizhi': '瑞智系统试用',
        'Zhenduan': '期易通交易诊断'
    }.get(module_key)
